Check if a file exists using Python
2504
11-May-2015
How do I check if a file exists, using Python, without using a try statement?
Aryan Kumar
01-May-2023To check if a file exists in Python, you can use the os.path module, which provides a range of functions for working with file paths. Here is an example:
In this example, we first import the os.path module. Then we define the name of the file we want to check (example.txt in this case). We use the os.path.isfile() function to check if the file exists. This function returns True if the file exists and is a regular file, and False otherwise.
If the file exists, we print the message "File exists". If the file does not exist, we print the message "File does not exist".
Note that this example assumes that the file is in the current working directory of the Python script. If the file is in a different directory, you will need to provide the full path to the file instead of just the filename.
Anonymous User
11-May-2015